package main

import (
	"common/config"
	"common/metrics"
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"math/rand"
	"net"
	"os"
	"time"
	"user/app"
	"user/pb"

	"google.golang.org/grpc"
)

var fileName = flag.String("conf", "application.yml", "conf file name")

func main() {

	// 1. 加载配置
	flag.Parse()
	config.InitConfig(*fileName)
	fmt.Println(*fileName)
	//2. 监控服务
	go func() {
		metrics.Serv(config.Conf.MetricPort)
	}()
	//3. 启动rpc服务
	//ctx, := context.WithTimeout(context.Background(), 5*time.Second)
	err := app.Run(context.Background())
	if err != nil {
		log.Println(err)
		os.Exit(-1)
	}

}

type myserv struct {
	pb.UnimplementedUserServiceServer
}

func (s *myserv) Register(ctx context.Context, req *pb.RegisterParams) (*pb.RegisterResponse, error) {
	json, _ := json.Marshal(req)
	fmt.Println(string(json))
	rand.Seed(time.Now().UnixNano())
	uid := string(rand.Intn(3000))
	return &pb.RegisterResponse{
		Uid: uid,
	}, nil
}

func rpccli() {
	lis, err := grpc.Dial(":1500", grpc.WithInsecure(), grpc.WithBlock())
	if err != nil {
		fmt.Printf("%v", err)
	}
	c := pb.NewUserServiceClient(lis)
	pm := &pb.RegisterParams{
		Account:       "11111",
		Password:      "passwweed",
		LoginPlatform: 12,
		SmsCode:       "dpwlw",
	}
	resp, err := c.Register(context.TODO(), pm)
	if err != nil {
		fmt.Printf("request err:%v", err)
	}
	fmt.Println(resp.GetUid())
}

func rpcserv() {
	lis, err := net.Listen("tcp", ":1500")
	if err != nil {
		fmt.Printf("RPC serv err:%v", err)
	}
	s := grpc.NewServer()
	pb.RegisterUserServiceServer(s, &myserv{})
	fmt.Printf("启动成功")
	if err = s.Serve(lis); err != nil {
		fmt.Printf("rpc  serv run err:%v", err)
	}

}
